package com.mallcai.bigdata.ladon.service.report.impl.handler;

import com.cake.bigdata.starter.exception.category.BusinessException;
import com.mallcai.bigdata.ladon.dpl.entity.common.Datasource;
import com.mallcai.bigdata.ladon.dpl.entity.report.Report;
import com.mallcai.bigdata.ladon.dpl.entity.report.ReportColumn;
import com.mallcai.bigdata.ladon.dpl.entity.report.ReportSql;
import com.mallcai.bigdata.ladon.service.common.IDatasourceService;
import com.mallcai.bigdata.ladon.service.report.IReportService;
import com.mallcai.bigdata.ladon.service.report.impl.ReportQueryConstants;
import com.mallcai.bigdata.ladon.service.report.impl.ReportQueryContext;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author feixy
 * @version 1.0
 * @date 2019-07-19 21:06
 */
@Component
@Order(500)
public class SetReportQueryObjectHandler extends AbstractReportQueryPreHandler {

    @Autowired
    private IReportService iReportService;

    @Autowired
    private IDatasourceService iDatasourceService;

    @Override
    public void preInternal(ReportQueryContext context) {
        Report report = iReportService.getByCode(context.getReportCode());
        if(report == null){
            throw new BusinessException(String.format("无效的code(%s),未找到相应的报表",context.getReportCode()));
        }
        ReportSql reportSql = iReportService.getSqlInfoById(report.getDetailSqlId());
        if(reportSql == null || StringUtils.isEmpty(reportSql.getText())){
            throw new BusinessException(String.format("无效的code(%s),报表未配置sql", context.getReportCode()));
        }
        if(reportSql.getDsId() == null){
            throw new BusinessException(String.format("无效的code(%s),报表未配置数据源", context.getReportCode()));
        }
        Datasource datasource = iDatasourceService.getById(reportSql.getDsId());
        if (datasource == null){
            throw new BusinessException(String.format("无效的code(%s),报表配置的数据源已失效", context.getReportCode()));
        }
        context.putInnerParam(ReportQueryConstants.KEY_REPORT, report);
        context.putInnerParam(ReportQueryConstants.KEY_REPORT_SQL, reportSql);
        context.putInnerParam(ReportQueryConstants.KEY_SQL, reportSql.getText());
        context.putInnerParam(ReportQueryConstants.KEY_DATA_SOURCE, datasource);

        List<ReportColumn> reportColumns = iReportService.getReportColumns(report.getId());
        context.putInnerParam(ReportQueryConstants.KEY_REPORT_SQL_COLUMNS, reportColumns);
    }

}
